package org.patto.main.api.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.patto.common.core.api.BaseApiService;
import org.patto.common.core.api.BaseResponse;
import org.patto.common.core.utils.IPUtils;
import org.patto.main.api.LoginService;
import org.patto.main.api.dto.req.LoginUserReqDto;
import org.patto.main.api.impl.entity.SysUser;
import org.patto.main.api.impl.entity.SysUserLoginLog;
import org.patto.main.manage.LoginLogManage;
import org.patto.main.api.impl.mapper.SysUserMapper;
import org.patto.common.core.utils.MD5Utils;
import org.patto.common.core.utils.RedisUtil;
import org.patto.main.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author songchuanfu
 * @ClassName LoginServiceImpl
 * @qq 18050164315
 * @addres 1802284273@qq.com
 * @微信: wx-suagcf
 */
@RestController
@Slf4j
public class LoginServiceImpl extends BaseApiService<JSONObject> implements LoginService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private LoginLogManage loginLogManage;

    @Override
    public BaseResponse<JSONObject> login(LoginUserReqDto loginUserReqDto) {
        String phoneNumber = loginUserReqDto.getPhoneNumber();
        // 1.验证参数是否为空
        if (StringUtils.isEmpty(phoneNumber)) {
            return setResultError("phoneNumber is null");
        }
        String password = loginUserReqDto.getPassword();
        if (StringUtils.isEmpty(password)) {
            return setResultError("password is null");
        }
        //select * from user where phoneNumber=''
        // 2.根据手机号码查询用户信息
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("phone_number", phoneNumber);
        SysUser sysUser = sysUserMapper.selectOne(sysUserQueryWrapper);
        if (sysUser == null) {
            return setResultError("该手机号码不存在!");
        }
        // 3.获取db存储加密密码
        String dbMd5Password = sysUser.getPassword();
        String userMd5Password = MD5Utils.md5(password + sysUser.getSalt());
        if (!dbMd5Password.equals(userMd5Password)) {
            return setResultError("密码错误!");
        }
        // --------------select * from user where phoneNumber='' and password='password'
        // 4.生成token 存放在redis中 value值=用户userid
        String token = TokenUtils.getToken();
        RedisUtil.setString(token, sysUser.getId() + "");
        JSONObject data = new JSONObject();
        data.put("token", token);
        // 5.登录后续流程
        /**
         * springmvc原理
         * 底层基于servlet封装
         * 调用springmvc封装servlet封装
         * 当前这个方法login 属于同一个线程
         */
        // 从当前线程中获取httpservletrequest对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // tomcat-nio8080-01
        SysUserLoginLog sysUserLoginLog = new SysUserLoginLog(sysUser.getId(), IPUtils.getIpAddr(request), new Date(),
                token, loginUserReqDto.getChannel(), loginUserReqDto.getEquipment());
        log.info("<登录日志:{}>", sysUserLoginLog);
        loginLogManage.asynLoginLog(sysUserLoginLog);
        return setResultSuccessData(data);
    }

    /**
     * 如果在方法上加上@Async  会导致失效？
     * 代理模式
     * 代理类实现接口--jdk动态代理  基于jdk动态代理实现的话 基于接口代理
     * 代理类继承某个类-----cglib代理
     */

}
